<?php
session_start();

//ini_set('display_errors', 1);

/* Using For Object Debug
$q[] = $_GET['q1'];
$q[] = $_GET['q2'];

var_dump( strtotime("Fri, 01 Jul 2011 12:32:34 -0700") );
var_dump( GetRSSMedia($q) );
*/
// s srequire "RSS/GoogleFeedItem.php";
//HTML parse XML.
function feedSearch($url_Parse) {
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$url_Parse);
	curl_setopt($ch, CURLOPT_FAILONERROR, true);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	curl_setopt($ch, CURLOPT_AUTOREFERER, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	$html = curl_exec($ch);

	if (!$html) {
		echo "<br />cURL error number:" .curl_errno($ch);
		echo "<br />cURL error:" . curl_error($ch);
		exit;
	}
	
	$doc = new DOMDocument();
	libxml_use_internal_errors(true);
	$doc->loadHTML($html);
    $xpath = new DOMXPath($doc);
    $feeds = $xpath->query("//head/link[@href][@type='application/rss+xml']/@href");
	
    $results = array();
	foreach($feeds as $feed) {
        $results[] = $feed->nodeValue;
    }
	
	if (count($results)==0) {
   	 	$feeds = $xpath->query("//head/link[@href][@type='application/atom+xml']/@href");
		
   	 	$results = array();
		foreach($feeds as $feed) { 
		    $results[] = $feed->nodeValue;
   		}
	}
	return $results[0];
}

function GetRSSMedia( $GoogleReader,$maxItems=null )
{
	$MediaQueueList = array();
	$returnArray=array();
	foreach( $GoogleReader as $url )
	{
		$Query = GetRSSData( $url,$maxItems );
		if( $Query['ErrorMsg'] == "Successful" )
			$MediaQueueList = array_merge( $MediaQueueList, $Query["Detail"]);
		else {
			
			$rssURL = feedSearch($url); 
			$Query = GetRSSData($rssURL,$maxItems);
			
			if( $Query['ErrorMsg'] == "Successful" )
			$MediaQueueList = array_merge( $MediaQueueList, $Query["Detail"]);
			else {
				var_dump( $Query['ErrorMsg'] );
			}
		}
		
	}
	
	usort($MediaQueueList, "cmp");
	//print_r($_SESSION['old']);
	
	return $MediaQueueList;
}

function cmp($a, $b)
{
    if ($a[0]['lastUpdate'] == $b[0]['lastUpdate']) {
        return 0;
    }
    return ($a[0]['lastUpdate'] > $b[0]['lastUpdate']) ? -1 : 1;
}
//if( isset( $_GET['q'] ))
//	$urlRSS = $_GET['q'];
//else
//	$urlRSS = "http://www.stylemepretty.com/feed/"; 
//print_r(GetRSSData("http://www.boston.com/bigpicture/index.xml"));
//print_r(GetRSSData("http://www.boston.com/bigpicture/index.xml"));

function filiterImg($content){
		 
		preg_match_all('/<img[^>]+>/i',$content, $imgAry);
		if(($imgAry > 0)&&(isset($imgAry[0][0]))){
		
			preg_match_all('/(src)=("[^"]*")/i',$returnValue = $imgAry[0][0], $img);
			
			for($k = 0;$k < 1; $k++){
				 $img_url = explode("src=",$img[0][$k]); 
				 
				 $done_img = str_replace('"', '', $img_url[1]);
				 if (strpos($done_img, 'http://') !== false) {
					 
					 set_error_handler("My_ErrorHandler");//Processed php error.
					 
					 $response = new Response();
					 $response->renderExceptions(true);
					 try {// Action code
					 	list($width, $height) = getimagesize($done_img);
						if($width > 1 && $height > 1)
							$returnValue = array($done_img, $width, $height);
					 } catch (Exception $e) {
						$returnValue = 0;
    					$response->setException($e); //Collect exception.
					 }
					 if ($response->isException()) {
  					 	 //Exception record.
					 }
					 $response->sendResponse(); // Display All result(contain Header, Exception, Body .etc)
				 }
			} 
			
		}else{
			$returnValue = 0;
		}
		return  $returnValue;
		
		
} 
	
function GetRSSData( $urlRSS,$maxItems=null )
{
   $url = "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=".$urlRSS."&scoring=h&num=$maxItems";
   
// sendRequest
// note how referer is set manually
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);	

	$body = curl_exec($ch);

	if (curl_errno($ch))
	{
		$ReturnValue = array( "ErrorCode" => curl_errno($ch), "ErrorMsg" => curl_error($ch));
	}
	else
	{
		// now, process the JSON string
		$json = json_decode($body);
		
		if( $json->responseStatus == 200 )
		{
			// now have some fun with the results...
			//$nSize = count( $json->responseData->feed->entries );
			
			if(parse_url($json->responseData->feed->link))
				$URL = parse_url($json->responseData->feed->link);
			else
				$URL = parse_url($json->responseData->feed->feedUrl);
			
			$MediaList = array();
			$k = 0;
			//var_dump($json->responseData->feed->entries);
			 $i=0;
			foreach( $json->responseData->feed->entries as $item )
			{
				
				$i++;
				
				$Media = array();
				
				// Title
				$strTitle = $item->title;
				// Web Link
				$urlWeb = $item->link;
				// Author
				$Author = $item->author;
				// Update Time
				if(  strtotime($item->publishedDate) )
				{
					$Timesamp = strtotime($item->publishedDate);
				}
				else
					$Timesamp = 946684800;
				// Description
				$strDescription = $item->contentSnippet;	
				// HTML
				$htmlDescription = $item->content;	
				// Categories
				$ArrayCategories = $item->categories;
				
				//BeMediaID 
				$ID = "RSS_". (string)$Timesamp;
				//$ID = "RSS". str_replace(array(".","/"), "", $URL['host']) . (string)$Timesamp;
				
				$MediaDetial = array(	"showNum"=>"$i","Head"=>"Media",	"ID"=>"",					"BeMediaID"=>$ID,		"MediaType"=>"HTML",	"CommentCount"=>"", 
										"WebLink"=>$urlWeb,	"Source"=>"GoogleReader",	"Author"=>$Author ,		"lastUpdate"=>$Timesamp);
				array_push( $Media, $MediaDetial );
				
				if($htmlDescription != ""){
					if(filiterImg($htmlDescription) != "") {
						$Image = filiterImg($htmlDescription);
						
						if ((strpos($Image[0], 'jpg') !== false)||(strpos($Image[0], 'png') !== false)||(strpos($Image[0], 'bmp') !== false))
							$Head = array( "Head"=>"beHtml", "Title"=>$strTitle, "Description"=>$htmlDescription, "ThumbnailImage"=>$Image[0], "ThumbnailWidth"=>$Image[1], "ThumbnailHeight"=>$Image[2]);
						else
							$Head = array( "Head"=>"beHtml", "Title"=>$strTitle, "Description"=>$htmlDescription);
					}
					else{
						//$Image = filiterImg($htmlDescription);	
						$Head = array( "Head"=>"beHtml", "Title"=>$strTitle, "Description"=>$htmlDescription);
					}
				}else{
					$Head = array( "Head"=>"beHtml", "Title"=>$strTitle, "Description"=>$htmlDescription);
				} 
			 	  
				array_push( $Media, $Head );
			
				array_push ($MediaList, $Media);
				//var_dump($Media);
			}//end foreach
			$ReturnValue = array( "ErrorCode" => 0, "ErrorMsg" => "Successful", "Detail" => $MediaList );			
		}
		else
		{
			$ReturnValue = array( "ErrorCode" => $json->responseStatus, "ErrorMsg" => $json->responseDetails );
		}
	}
	curl_close($ch);
	//echo $ReturnValue;
	
	return $ReturnValue;
}



?>